// 接口地址：https://www.apifox.cn/apidoc/shared-36f0cbc0-9064-44bc-850a-805e263bf494/api-25827426
//1.封装获取元素的函数
// function qs(ele) {
//     //将获取到的元素return 返回出去
//     return document.querySelector(ele)
// }
//简写
const qs = ele => document.querySelector(ele)
//要获取什么元素就传进去
// console.log(qs('#province'));

//2.配置请求根路径
axios.defaults.baseURL = 'http://124.223.14.236:3001/api'

//渲染省市区数据
async function render() {
    //3.------------------------获取省数据---------------------------
    const { data: { data: provinceData } } = await axios.get('/city/province')
    // console.log(res);
    console.log(provinceData);
    //map+join渲染数据
    const provinceStr = provinceData.map(item => {
        return `<option value="${item.province}">${item.name}</option>`
    }).join('')
    qs('#province').innerHTML = '<option value="">请选择省份</option>' + provinceStr
    //默认显示安徽省
    qs('#province').value = 34

    //4.------------------------获取市数据-----------------------------
    const { data: { data: cityData } } = await axios.get('/city/city', { params: { provinceCode: '34' } })
    console.log(cityData);
    const cityStr = cityData.map(item => {
        return `<option value="${item.city}">${item.name}</option>`
    }).join('')
    qs('#city').innerHTML = '<option value="">请选择省份</option>' + cityStr
    //默认显示合肥市
    qs('#city').value = '01'

    //5.------------------------获取区数据-----------------------------
    const { data: { data: areaData } } = await axios.get('/city/area', { params: { provinceCode: '34', cityCode: '01' } })
    console.log(areaData);
    const areaStr = areaData.map(item => {
        return `<option value="${item.area}">${item.name}</option>`
    }).join('')
    qs('#county').innerHTML = '<option value="">请选择区县</option>' + areaStr
    qs('#county').value = '02'
}
render()

//注册省的 changge事件
//声明一个变量存储到省的 编码
let provinceCode = null
qs('#province').addEventListener('change', async function () {
    console.log(this.value);//省 对应的编码
    provinceCode = this.value
    //发送ajax请求，获取省对应的城市
    const { data: { data: cityData } } = await axios.get('/city/city', { params: { provinceCode } })
    console.log(cityData);
    const cityStr = cityData.map(item => {
        return `<option value="${item.city}">${item.name}</option>`
    }).join('')
    qs('#city').innerHTML = '<option value="">请选择省份</option>' + cityStr
    qs('#county').innerHTML = '<option value="">请选择区县</option>'
})

//注册 市 的change事件
qs('#city').addEventListener('change', async function () {
    console.log(this.value);//城市对应的编码
    //发送ajax请求，获取城市对应的区
    const { data: { data: areaData } } = await axios.get('/city/area', { params: { provinceCode, cityCode: this.value } })
    console.log(areaData);
    const areaStr = areaData.map(item => {
        return `<option value="${item.area}">${item.name}</option>`
    }).join('')
    qs('#county').innerHTML = '<option value="">请选择区县</option>' + areaStr

})


